package com.yuan.fullstackback.controller;

import com.yuan.fullstackback.pojo.SysCategory;
import com.yuan.fullstackback.service.impl.SysCategoryServiceImpl;
import com.yuan.fullstackback.utils.AjaxResult;
import com.yuan.fullstackback.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 分类信息
 */
@RestController
@RequestMapping("/system/category")
public class SysCategoryController {

    @Autowired
    private SysCategoryServiceImpl sysCategoryService;

    //查询所以分类【分页查询】
    @GetMapping("/list")
    public AjaxResult selectAllCategory() {
        List<SysCategory> categories = sysCategoryService.selectAllCategory();
        if (categories.isEmpty()) {
            return AjaxResult.success(0);
        }
        return AjaxResult.success(categories);
    }

    //新增分类
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysCategory sysCategory) {
        //数据库中是否有数据  根据名称查询是否存在
        if (sysCategoryService.checkCategoryCount() != 0 && sysCategoryService.checkCategoryUnique(sysCategory.getCategoryName()) == 0)
            return AjaxResult.error("新增分类'" + sysCategory.getCategoryName() + "'失败，分类名称已存在");
        Map<String, Object> claims = ThreadLocalUtil.get();
        sysCategory.setCreateUser((Integer) claims.get("userId"));
        sysCategory.setDelFlag("0");
        //添加到数据库
        if (sysCategoryService.insertCategory(sysCategory) != 1) {
            return AjaxResult.error("添加失败");
        }
        return AjaxResult.success("添加成功");
    }

    //修改分类
    @PutMapping("/update")
    public AjaxResult update(@Validated @RequestBody SysCategory sysCategory) {
        //根据名称查询是否存在
        if (sysCategoryService.checkCategoryUnique(sysCategory.getCategoryName()) == 0) {
            return AjaxResult.error("修改分类'" + sysCategory.getCategoryName() + "'失败，分类名称已存在");
        }
        //添加到数据库
        if (sysCategoryService.updateCategory(sysCategory) != 1) {
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success("修改成功");
    }

    //删除分类
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam Long categoryId) {
        //根据Id查询是否存在
        if (!sysCategoryService.checkCategoryById(categoryId)) {
            return AjaxResult.error("删除分类'" + categoryId + "'失败，分类不存在");
        }
        //查询该分类下是否有文章存在，如果有则不可以删除
        if (sysCategoryService.checkCategoryExistArticle(categoryId) != 0) {
            return AjaxResult.error("分类下存在文章,不允许删除");
        }
        //更新数据到数据库
        if (sysCategoryService.deleteCategoryById(categoryId) != 1) {
            return AjaxResult.error("删除失败");
        }
        return AjaxResult.success("删除成功");
    }

}
